package com.shawn.integeration.batch.file.reader;

import com.shawn.integeration.business.student.model.Student;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

/**
 * @author shawn
 * @description:文件读取器
 * @date 2024/1/13
 */
@Component
public class StudentFileItemReaderBuilder {

    public ItemReader<Student> build() {
        FlatFileItemReader<Student> reader = new FlatFileItemReader<>();
        // 设置文件资源地址
        reader.setResource(new ClassPathResource("static/student.txt"));

        // 忽略第一行
        reader.setLinesToSkip(1);

        // AbstractLineTokenizer的三个实现类之一，以固定分隔符处理行数据读取,
        // 使用默认构造器的时候，使用逗号作为分隔符，也可以通过有参构造器来指定分隔符
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();

        // 设置属性名，类似于表头
        tokenizer.setNames("id", "name", "age", "sex", "birthday");

        // 将每行数据转换为TestData对象
        DefaultLineMapper<Student> mapper = new DefaultLineMapper<>();

        // 设置LineTokenizer
        mapper.setLineTokenizer(tokenizer);

        // 设置映射方式，即读取到的文本怎么转换为对应的POJO
        mapper.setFieldSetMapper(fieldSet -> {
            Student student = new Student();
            student.setId(fieldSet.readLong("id"));
            student.setName(fieldSet.readString("name"));
            student.setAge(fieldSet.readInt("age"));
            student.setSex(fieldSet.readInt("sex"));
            student.setBirthday(fieldSet.readDate("birthday"));
            return student;
        });
        reader.setLineMapper(mapper);
        return reader;
    }
}
